<template>
  <div>
    <el-page-header content="编辑产品" @back="handleBack()" title="产品管理" />

    <el-form ref="productFormRef" :model="productForm" :rules="productFormRules" label-width="80px" status-icon class="productForm">
      <el-form-item label="产品名称" prop="title">
        <el-input v-model="productForm.title" />
      </el-form-item>
      <el-form-item label="简要描述" prop="introduction">
        <el-input v-model="productForm.introduction" type="textarea" />
      </el-form-item>
      <el-form-item label="详细描述" prop="detail">
        <el-input v-model="productForm.detail" type="textarea" />
      </el-form-item>
      <el-form-item label="产品图片" prop="cover">
        <Upload :avatar="productForm.cover" @myChange="handleUploadChange" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm()">更新产品</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import upload from '@/util/upload'
import Upload from '@/components/upload/Upload.vue'
import axios from 'axios'

const router = useRouter()
const route = useRoute()
const productFormRef = ref()
const productForm = reactive({
  title: '',
  introduction: '',
  detail: '',
  cover: '',
  file: null
})
const productFormRules = reactive({
  title: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
  introduction: [{ required: true, message: '请输入简要描述', trigger: 'blur' }],
  detail: [{ required: true, message: '请输入详细描述', trigger: 'blur' }],
  cover: [{ required: true, message: '请上传产品图片', trigger: 'blur' }]
})
// 选择完图片后的回调
const handleUploadChange = (file) => {
  productForm.cover = URL.createObjectURL(file)
  productForm.file = file
}
// 添加新闻的回调
const submitForm = () => {
  productFormRef.value.validate(async (valid) => {
    if (valid) {
      // 后台通信
      await upload('/adminapi/product/list', productForm)
      router.push(`/product-manage/productlist`)
    }
  })
}
// 返回回调
const handleBack = () => {
  router.back()
}
onMounted(async () => {
  // 取当前页面数据
  // console.log(route.params.id)
  const res = await axios.get(`adminapi/product/list/${route.params.id}`)
  // console.log(res.data.data[0])
  Object.assign(productForm, res.data.data[0])
})
</script>

<style lang="scss" scoped>
.el-form {
  margin-top: 50px;
}
</style>
